<?php
include('common_include.php');
include('lib/util/order_include.php');

$error_msg = "";

if (!session_is_registered('my_cart'))
	session_start();


// =================== GET HANDLER =======================
// =======================================================
$arrProdCode = "";

// adding product code to the session
if ($_GET['prodCode'])
{
	addToCart($_GET['prodCode']);
}

if ($_SESSION['my_cart'])
{
	$arrProdCode = explode(';', $_SESSION['my_cart']);
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<title>Winning Marketing</title>
	<link href="style.css" rel="stylesheet" type="text/css" />

	<script language="JavaScript" src="scripts/common.js"></script>
	<script type="text/javascript">
	function isNumberKey(evt)
	{
		var charCode = (evt.which) ? evt.which : event.keyCode
		if (charCode > 31 && (charCode < 48 || charCode > 57))
			return false;

		return true;
    }

    function calculate(obj, idx)
    {
    	// Calculate SubTotal
    	if (obj.value == "")
		    obj.value = 0;

		unitPrice = document.getElementsByName('unitPrice[]');
		shipmentFee = document.getElementsByName('shipmentFee[]');
		subTotal = document.getElementsByName('subTotal[]');
		total = document.getElementsByName('total[]');
		qty = document.getElementsByName('qty[]');
		postAllowedIndArr = document.getElementsByName('postAllowedInd[]');
		shipmentFeeArr = document.getElementsByName('shipmentFee[]');
		postageArr = document.getElementsByName('postage[]');
		

		tmpShiptmentFee = 0;
		if (postAllowedIndArr[idx].value == "Y" && document.settlementForm.cDlvMode.value == "POST") {
			tmpShiptmentFee = parseFloat(postageArr[idx].value);
		}

    	subTotal[idx].value = format_number(parseFloat(obj.value) * parseFloat(unitPrice[idx].value) + 
    	    								parseFloat(obj.value) * tmpShiptmentFee, 2); 

    	var shipmentFeeTotal = 0;
    	// Calculate Total
    	idxCount = qty.length;
    	total = 0;
    	for (i=0; i<idxCount; i++)
    	{
    		tmpShiptmentFee = 0;
    		if (postAllowedIndArr[i].value == "Y" && document.settlementForm.cDlvMode.value == "POST") {
    			tmpShiptmentFee = parseFloat(postageArr[i].value);
    		}
    		shipmentFeeSubTotal = parseFloat(qty[i].value) * tmpShiptmentFee;
    		shipmentFeeArr[i].value = format_number(shipmentFeeSubTotal, 2);
    		total = total + parseFloat(subTotal[i].value);
    		shipmentFeeTotal = shipmentFeeTotal + shipmentFeeSubTotal;
    	}
    	document.settlementForm.total.value = format_number(total, 2);
    	document.settlementForm.shipmentFeeTotalText.value = format_number(shipmentFeeTotal, 2);
    }

    function recalculateAll() {
		unitPrice = document.getElementsByName('unitPrice[]');
		shipmentFee = document.getElementsByName('shipmentFee[]');
		subTotal = document.getElementsByName('subTotal[]');
		total = document.getElementsByName('total[]');
		qty = document.getElementsByName('qty[]');
		postAllowedIndArr = document.getElementsByName('postAllowedInd[]');
		shipmentFeeArr = document.getElementsByName('shipmentFee[]');
		postageArr = document.getElementsByName('postage[]');

    	var shipmentFeeTotal = 0;
    	// Calculate Total
    	idxCount = qty.length;
    	total = 0;
    	for (i=0; i<idxCount; i++)
    	{
    		tmpShiptmentFee = 0;
			if (postAllowedIndArr[i].value == "Y" && document.settlementForm.cDlvMode.value == "POST") {
				tmpShiptmentFee = parseFloat(postageArr[i].value);
			}
			shipmentFeeSubTotal = parseFloat(qty[i].value) * tmpShiptmentFee;
    		shipmentFeeArr[i].value = format_number(shipmentFeeSubTotal, 2);
			
    		subTotal[i].value = format_number(parseFloat(qty[i].value) * parseFloat(unitPrice[i].value) + 
    				parseFloat(qty[i].value) * tmpShiptmentFee, 2); 
    		total = total + parseFloat(subTotal[i].value);
    		shipmentFeeTotal = shipmentFeeTotal + shipmentFeeSubTotal;
    	}
    	document.settlementForm.total.value = format_number(total, 2);
    	document.settlementForm.shipmentFeeTotalText.value = format_number(shipmentFeeTotal, 2);
    }

	function deleteConfirmation(status, prdCode)
	{
		var answer = confirm("Are you sure you wish to remove this item?")
		if (answer)
		{
			SubmitForm(status, prdCode);
		}
	}

	function emailValidate(form_id,email) {

	   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   var address = document.forms[form_id].elements[email].value;
	   if(reg.test(address) == false) {
	      return false;
	   }
	   return true;
	}

	function FormValidation()
		{
			qty = document.getElementsByName('qty[]');
			cbColor = document.getElementsByName('color[]');
			cbSize = document.getElementsByName('size[]');
			cName = document.settlementForm.cName;
			cAddress = document.settlementForm.cAddress;
			cContact = document.settlementForm.cContact;
			cEmail = document.settlementForm.cEmail;
			cVEmail = document.settlementForm.cVEmail;

			msg = "";
			idxCount = qty.length;
			for (i=0; i<idxCount; i++)
			{
				if (cbSize[i].value=="")
					msg = msg + "Please key in size for item-" + (i+1) + "\n";
				if (cbColor[i].value=="")
					msg = msg + "Please key in color for item-" + (i+1) + "\n";
			}


			if (trim(cName.value) == "")
				msg = msg + "Please key in your name \n";
			if (trim(cAddress.value) == "")
				msg = msg + "Please key in your address \n";
			if (trim(cContact.value) == "")
				msg = msg + "Please key in your contact \n";
			if (trim(cEmail.value) == "")
				msg = msg + "Please key in your email \n";
			if (trim(cVEmail.value) == "")
				msg = msg + "Please key in your verification email \n";
			if (!emailValidate('settlementFormID', 'cEmail') || !emailValidate('settlementFormID', 'cVEmail'))
				msg = msg + "Invalid Email Address \n";
			if (trim(cVEmail.value) != trim(cEmail.value))
				msg = msg + "Email and Verification Email is not tally \n";

			if (msg != "")
			{
	    		alert(msg);
	    		return false;
	    	}

	    	return true;
	}

	function deliveryModeOnChange() {
		if (document.settlementForm.cDlvMode.value == "POST") {
			alert("Please note that, \nonly those products with Shipping Available indicated as 'Y' will be sent to you,\nthe rest will need self collect. ");
		}
		recalculateAll();
	}

	function SubmitForm(status, prdCode)
	{
		if (status == 'S' && !FormValidation())
			return false;
		else if (status == 'D')
			document.settlementForm.delProdCode.value=prdCode;

		document.settlementForm.postStatus.value=status;
		document.settlementForm.submit();

	}

	function bodyOnload() {
		recalculateAll();
	}
	</script>
</head>
<body onload="bodyOnload();">
<div id="container">
<div id="main">
	<div id="header"><img src="images/template/skitemplate_03.gif" width="753" height="341" /></div>
	<div id="nav">
		<ul>
			<li><a href="index.php">About Us </a></li>
			<li><a href="product.php">Products</a></li>
			<li><a href="wholesale.html">Wholesale / Export</a></li>
			<li><a href="members.html">Members Area </a></li>
			<li><a href="contactUs.html">Enquiry / Contact us</a></li>
			<li><a href="Settlement.php">Shopping Cart</a></li>
		</ul>
	</div>
	<div id="content">
	<form action="SettlementController.php" name="settlementForm" id="settlementFormID" method="post">
		<input type="hidden" name="postStatus" value=""/>
		<input type="hidden" name="delProdCode" value=""/>

		<table width="100%" border="0" cellspacing="2" align="center">
		<tr><td>&nbsp;</td></tr>
		<tr><td align="center"><h2>Settlement</h2></td></tr>
		<tr>
			<td>&nbsp;</td>
		</tr>

		<?php
		if ($arrProdCode == "")
		{
		?>
			<tr>
				<td>No Product In the List. <a href="product.php">Click here</a> to choose your product </td>
			</tr>
		<?php
		}
		else
		{
		?>
		<tr>
			<td>
				<table width="90%" border="1" cellspacing="2">
				<tr>
					<th width="3%" align="center">S/N</th>
					<th width="7%" align="center">Product Code</th>
					<th width="40%" align="center">Product Name</th>
					<th width="5%" align="center">Shipping Available</th>
					<th width="3%" align="center">Size</th>
					<th width="5%" align="center">Color</th>
					<th width="2%" align="center">Qty</th>
					<th width="10%" align="center">Unit Price</th>
					<th width="10%" align="center">Shipment Fee</th>
					<th width="10%" align="center">Sub-Total</th>
					<th width="5%" align="center">Delete</th>
				</tr>

				<?php
				$total = 0;
				$shipmentFeeTotal = 0;
				$idx = 0;
				foreach ($arrProdCode as $prdCode)
				{
					$dao = new SQLitePersistence();
					$aProduct = $dao->getProductsByProdCode($prdCode);
					$total = $total + $aProduct->getUnitPrice();
					
					$tmpPostage = 0;;
					if ($aProduct->getPostAllow() == "Y") {
						$tmpPostage = $aProduct->getPostage();
					}
					
					$shipmentFeeTotal = $shipmentFeeTotal + $tmpPostage;
				?>
					<tr>
						<td align="left"><?php echo ($idx + 1); ?></td>
						<td align="left">
							<?php echo $prdCode; ?>
							<input type="hidden" name="prdCode[]" value="<?php echo $prdCode; ?>"/>
							<input type="hidden" name="prdId[]" value="<?php echo $aProduct->getProductId(); ?>"/>
						</td>
						<td align="left"><?php echo $aProduct->getProductName(); ?></td>
						<td align="center">
							<?php echo $aProduct->getPostAllow(); ?>
							<input type="hidden" name="postAllowedInd[]" value="<?php echo $aProduct->getPostAllow(); ?>"/>
							<input type="hidden" name="postage[]" value="<?php echo $aProduct->getPostage() ?>"/>
						</td>
						<td align="left">
							<select name="size[]" style="width: 40px">
							<?php
							$arrSize = $aProduct->getSizeOpt();
							$arrSize = explode(',', $arrSize);
							foreach($arrSize as $size)
							{
								echo "<option value='$size'>$size</option>";
							}
							?>
							</select>

						</td>
						<td align="left">
							<select name="color[]" style="width: 70px">
							<?php
							$arrColor = $aProduct->getColorOpt();
							$arrColor = explode(',', $arrColor);
							foreach($arrColor as $color)
							{
								echo "<option value='$color'>$color</option>";
							}
							?>
							</select>

						</td>
						<td align="left"><input type="text" name="qty[]" maxlength="10" value="1" size="2" onblur="calculate(this, <?php echo $idx; ?>)" onkeypress="return isNumberKey(event)" /></td>
						<td align="left">
							<input type="text" name="unitPrice[]" style="text-align:right" maxlength="10" size="5" value="<?php echo number_format($aProduct->getUnitPrice(), 2, '.', ''); ?>" readonly />
						</td>
						<td align="left">
							<input type="text" name="shipmentFee[]" style="text-align:right" maxlength="10" size="5" value="<?php echo number_format($tmpPostage, 2, '.', ''); ?>" readonly/>
						</td>
						<td align="left">
							<input type="text" name="subTotal[]" style="text-align:right" maxlength="10" size="5" value="<?php echo number_format($aProduct->getUnitPrice() + $tmpPostage, 2, '.', ''); ?>" readonly/>
						</td>
						<td><a href="#" onclick="deleteConfirmation('D', '<?php echo $prdCode; ?>')">Delete</a></td>
					</tr>
				<?php
					$idx += 1;
				}

				unset($dao);
				?>
				<tr>
					<td colspan="8" align="right">Total:&nbsp;</td>
					<td><input type="text" name="shipmentFeeTotalText" style="text-align:right" maxlength="10" value="<?php echo number_format($shipmentFeeTotal, 2, '.', ''); ?>" size="5" readonly /></td>
					<td><input type="text" name="total" style="text-align:right" maxlength="10" value="<?php echo number_format($total, 2, '.', ''); ?>" size="5" readonly /></td>
					<td>&nbsp;</td>
				</tr>

				</table>

			</td>
		</tr>
		<tr>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td>
				<table width="90%" border="1" cellspacing="2">
				<tr>
					<th width="20%" align="left">Name</th>
					<td><input type="text" name="cName" maxlength="60" /></td>
				</tr>
				<tr>
					<th width="20%" align="left">Address</th>
					<td><textarea name='cAddress' rows="5" cols="50"></textarea></td>
				</tr>
				<tr>
					<th width="20%" align="left">Contact Number</th>
					<td><input type="text" name="cContact" maxlength="20" /></td>
				</tr>
				<tr>
					<th width="20%" align="left">Email</th>
					<td><input type="text" name="cEmail" maxlength="60" /></td>
				</tr>
				<tr>
					<th width="20%" align="left">Confirm Email</th>
					<td><input type="text" name="cVEmail" maxlength="60" /></td>
				</tr>
				<tr>
					<th width="20%" align="left">Delivery Mode</th>
					<td>
						<select name="cDlvMode" onchange="deliveryModeOnChange();">
							<option value="SELF COLLECT" selected>SELF COLLECT</option>
							<option value="POST">POST</option>
						</select>
					</td>
				</tr>
				<tr>
					<th width="20%" align="left">Payment Mode</th>
					<td>
						<select name="cPayMode">
							<option value="ONLINE">Online (Paypal / Credit Card)</option>
							<option value="OFFLINE">Offline Bank Transfer</option>
						</select>
					</td>
				</tr>
				<tr>
					<th width="20%" align="left">Remark</th>
					<td><textarea name='cRemark' rows="5" cols="50"></textarea></td>
				</tr>
				</table>
			</td>
		</tr>
		<tr>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td><input type="button" value="Submit" name="btnSubmit" onclick="SubmitForm('S')"/>&nbsp;&nbsp;<input type="button" value="Back" name="btnBack" onclick="SubmitForm('B')" /></td>
		</tr>
		<?php
		}
		?>
		</table>
	</form>
	</div>
</div>
	<div id="footer">
		<ul>
			<li><a href="index.php">About Us | </a></li>
			<li><a href="product.php">Products | </a></li>
			<li><a href="wholesale.html">Wholesale / Export | </a></li>
			<li><a href="members.html">Members Area | </a></li>
			<li><a href="contactUs.html">Enquiry / Contact Us | </a></li>
			<li><a href="Settlement.php">Shopping Cart</a></li>
		</ul>
		<span>copyright of Winning Marketing</span>
	</div>
    <p>&nbsp;</p>
</div>
</body>
</html>